const router = require('koa-router')()
const {exec}=require('../db')
const jwt=require('jsonwebtoken')
const {md5PWD}=require('../utils/utility')

router.post('/signIn', async (ctx, next) => {
  const {username,password,nickname}=ctx.request.body
  let signInsql=`SELECT * FROM userlist WHERE username='${username}'`
  const data=await exec(signInsql)
  if(data.length>0){
    ctx.body={
      code:401,
      message:'此账号已注册'
    }
  }else{
    let addUsersql=`INSERT INTO userlist (username, password, nickname, id) VALUES ('${username}', '${md5PWD(password)}', '${nickname}', NULL);`
    await exec(addUsersql)
    ctx.body={
      code:200,
      message:'注册成功'
    }
  }
  
})
router.post('/login',async(ctx,next)=>{
  const {username,password}=ctx.request.body
  let loginSql=`SELECT * FROM userlist WHERE username='${username}' and password='${md5PWD(password)}'`
  const users=await exec(loginSql)
  // console.log(users[0].username)
  if(users.length>0){
    ctx.body={
      name:users[0].nickname,
      code:200,
      message:'登录成功',
      token:jwt.sign({username:users[0].username},'1906A')
    }
  }else{
    ctx.body={
      code:404,
      message:'登录失败'
    }
  }
})


module.exports = router
